package com.khaled.protclass.model.util;

import java.util.Hashtable;
import java.util.StringTokenizer;

public class UtilProtein
{
	public static Hashtable<String, String> readProteins(String proteinsFile)
	{
		String[] fastaLines = proteinsFile.split("\n");
		Hashtable<String, String> htProteins = new Hashtable<String, String>();

		String proteinId = null;
		String proteinSequence = "";

		for (String line : fastaLines)
		{
			String strLine = line.trim();

			if ("".equals(strLine))
			{
				if (proteinId != null)
				{
					addProtein(htProteins, proteinId, proteinSequence);

					proteinSequence = "";
					proteinId = null;
				}
			}
			else if (strLine.startsWith(">"))
			{
				if (proteinId != null)
				{
					addProtein(htProteins, proteinId, proteinSequence);

				}
				proteinId = strLine.trim();
				/*
				 * sometimes proteinId contains more information rather than its
				 * id so naming the protein with all of these information may
				 * cause some problems specially while saving it in a file (the
				 * file name will be too long)
				 * 
				 * so I assume that protein information is splited by | sign and
				 * the protein id is located in the second item
				 * 
				 * ex: >gi|10173129|dbj|BAB04235.1| surface adhesin A precursor
				 * [Bacillus halodurans] the protein Id is 10173129
				 * 
				 * TODO: consider other representations
				 */

				StringTokenizer proSplits = new StringTokenizer(proteinId, "|");
				if (proSplits.countTokens() > 1)
				{
					proSplits.nextToken();

					proteinId = ">" + proSplits.nextToken();
				}
				// /////////////////////////////////////////////////////////////////

				proteinSequence = "";
			}
			else
			{
				proteinSequence += strLine;
			}
		}
		if (proteinId != null)
		{
			addProtein(htProteins, proteinId, proteinSequence);
		}

		return htProteins;
	}

	private static void addProtein(Hashtable<String, String> htProteins, String protId, String protSequence)
	{
		while (htProteins.contains(protId))
		{
			protId = protId + "+";
		}

		htProteins.put(protId, protSequence);
	}
}
